import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { responseTrim, requestTrim } from '@/utils/tool'
import { getToken } from '@/utils/auth'
import { deepClone } from '@/utils'

// create an axios instance
const service = axios.create({
  baseURL: '', // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 15000 * 2 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    if (config.method === 'post' && !(config.data instanceof FormData)) {
      config.data = requestTrim(deepClone(config.data))
    }
    // do something before request is sent
    if (store.getters.token && config.url.indexOf('candidate/client/version') === -1 && config.url.indexOf('monitor/oss/exam/token') === -1) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      // console.log('token', getToken())
      getToken() && (config.headers['Authorization'] = 'Bearer ' + getToken())
    }
    return config
  },
  error => {
    console.log(error)
    // do something with request error
    // console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    // if the custom code is not 20000, it is judged as an error.
    if (res.code && res.code !== 0) {
      if (res.code === 40002) {
        Message({
          message: res.message
        })
      } else if (res.code === -777) {
        Message({
          message: '出现错误，请联系管理员！',
          type: 'error'
        })
        return res
      } else {
        Message({
          message: res.message || 'Error',
          type: 'error',
          duration: 5 * 1000
        })
        return res
      }

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 3) {
        // to re-login
        MessageBox.confirm(
          '您已经退出登录，您可以重新登录，也可以点击取消停留在该页面？',
          '退出登录提示',
          {
            confirmButtonText: '重新登录',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }

      if (response.request.responseURL.indexOf('ent/sms/send') > -1) {
        return responseTrim(res)
      } else {
        return Promise.reject(res.message || 'Error')
      }
    } else if (response.data instanceof Blob) {
      return res
    } else if (response.headers['content-type'] === 'text/plain') {
      return res
    } else {
      return responseTrim(res)
    }
  },
  error => {
    if (!window.navigator.onLine) {
      Message({
        message: '网络断开，请检查网络',
        type: 'error'
      })
      return Promise.reject(error)
    } else {
      Message({
        message: error.errmsg || '服务繁忙，请稍后再试',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(error)
    }
  }
)

export default service
